import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState, useEffect, useRef, ComponentType } from "react";
import Header from "../../myComponent/header";
import useGetCurrentSystem from "../../../hooks/useGetCurrentSystem";
import { useDocumentTitle } from "@/utils/myUtils";
import { Divider, Modal, Switch, Tabs } from "antd-mobile";
import useGetUserInfo from "../../../hooks/useGetUserInfo";
import { changeSystemStatusService } from "@/network/servers";
import LgButton from "@/pages/components/button";
import PubSub from "pubsub-js";
import { cloneDeep } from "lodash";
import { useDispatch } from "react-redux";
import "../common.scss";
import styles from "./index.modules.scss";

function App() {
  const dispatch = useDispatch();
  const { schoolId } = useGetUserInfo() as any;
  const currentSystem = useGetCurrentSystem();
  const { sysId, sysName = "", sceneList = [] } = currentSystem;

  useDocumentTitle(sysName, false);

  const firstKey = sceneList[0].sceneId || '';
  const firstEventList = sceneList[0].eventList || [];
  const [selectedTab, setSelectedTab] = useState(firstKey);
  const [eventList, setEventList] = useState(firstEventList);
  const firstSceneName = sceneList[0].sceneName || 'xxxxx';

  const [activeTabLineWith, setActiveTabLineWith] = useState(firstSceneName.length * 14);

  //切换tab
  function handleTabChange(key) {
    setSelectedTab(key);
    const currentScene = sceneList.find((s) => s.sceneId === key) || {};
    const currentEventList = currentScene.eventList || [];
    const { sceneName = "xxxxx" } = currentScene;
    setActiveTabLineWith(sceneName.length * 14);

    setEventList(currentEventList);
  }

  // 改变系统推送状态
  function handleChangeSystemStatus(
    type: string,
    value: boolean,
    eventId: string
  ) {
    const flag = value ? "1" : "0";
    changeSystemStatusService({ sysId, [type]: flag, eventId, schoolId }).then(
      (result) => {
        if (result.code == 200) {
          Taro.showToast({
            title: `消息推送${value?"开启":"关闭"}成功`,
          });
        }

        // 修改当前系统的开关状态
        const resetSystem = cloneDeep(currentSystem);
        const { sceneList = [] } = resetSystem;
        sceneList.forEach((s) => {
          if (s.sceneId === selectedTab) {
            const { eventList = [] } = s;
            eventList.forEach((e) => {
              if (e.eventId === eventId) {
                e[type] = flag;
              }
            });
            setEventList(eventList);
          }
        });
        dispatch({
          type: "SET_CURRENTSYSTEM",
          data: resetSystem,
        });
        //刷新
        PubSub.publish("refresh_setting");
      }
    );
  }

  //通知对象提示
  function handelShowTip(text) {
    Modal.show({
      content: (
        <View className={styles["tip-modal"]}>
          <View className={styles.title}>通知对象</View>
          <View style={{ textAlign: "center" }}>{text}</View>
          <View className={styles.close}>
            <LgButton
              type="D"
              width={420}
              height={72}
              onClick={() => Modal.clear()}
            >
              关闭
            </LgButton>
          </View>
        </View>
      ),
      bodyStyle: {
        width: Taro.pxTransform(560),
      },
      closeOnMaskClick: true,
    });
  }

  useEffect(() => {
    return () => {
      // 返回 对首页进行刷新
      PubSub.publish("refresh_setting");
    };
  }, []);

  return (
    <View className={styles.container}>
      <Header title={sysName} isLeft={true} needHome={false} />
      <View className={styles["content-wrapper"]}>
        <View className={styles.tabs}>
          <Tabs
            activeKey={selectedTab}
            stretch={false}
            activeLineMode={"fixed"}
            onChange={(key) => handleTabChange(key)}
            style={{
              "--active-line-height": Taro.pxTransform(4),
              "--fixed-active-line-width": Taro.pxTransform(activeTabLineWith),
              "--content-padding": "0",
              "--title-font-size": Taro.pxTransform(28),
            }}
          >
            {sceneList.map((s) => {
              const { sceneId, sceneName } = s;
              return (
                <Tabs.Tab
                  key={sceneId}
                  title={
                    <View className={styles["tab-wrapper"]}>{sceneName}</View>
                  }
                ></Tabs.Tab>
              );
            })}
          </Tabs>
        </View>
        <View className={styles["tab-content"]}>
          {eventList.map((e) => {
            const {
              eventId = "",
              eventContent,
              appletsPush = "1",
              todoPush = "1",
              sysPush = "1",
              appPush = "1",
              mailPush = "1",
              smsPush = "1",
              noticeTarget,
            } = e;

            return (
              <View className={styles["event-wrapper"]}>
                <View className={styles["event-name"]}>
                  <View>{eventContent}</View>
                  {/* <View
                    className={styles.tip}
                    onClick={() => handelShowTip(noticeTarget)}
                  ></View> */}
                </View>
                <View className={styles['notice-target']}>通知对象: {noticeTarget}</View>
                <Divider
                  style={{
                    margin: `${Taro.pxTransform(24)} 0 0 0`,
                  }}
                />
                <View className={styles["event-content"]}>
                  {/* 公众号消息推送 */}
                  {appletsPush !== "-1" ? (
                    <PushOptionItem
                      pushStatus={appletsPush}
                      eventId={eventId}
                      optionType="appletsPush"
                      handleChangeSystemStatus={handleChangeSystemStatus}
                    />
                  ) : (
                    ""
                  )}

                  {/* 系统消息选项 */}
                  {sysPush !== "-1" ? (
                    <>
                      <Divider
                        style={{
                          display: `${appletsPush !== "-1" ? "" : "none"}`,
                          margin: `0 0 0 ${Taro.pxTransform(15)}`,
                        }}
                      />
                      <PushOptionItem
                        pushStatus={sysPush}
                        eventId={eventId}
                        optionType="sysPush"
                        handleChangeSystemStatus={handleChangeSystemStatus}
                      />
                    </>
                  ) : (
                    ""
                  )}

                  {/* 待办事项推送 */}
                  {todoPush !== "-1" ? (
                    <>
                      <Divider
                        style={{
                          display: `${
                            appletsPush !== "-1" || sysPush !== "-1"
                              ? ""
                              : "none"
                          }`,
                          margin: `0 0 0 ${Taro.pxTransform(15)}`,
                        }}
                      />
                      <PushOptionItem
                        pushStatus={todoPush}
                        eventId={eventId}
                        optionType="todoPush"
                        handleChangeSystemStatus={handleChangeSystemStatus}
                      />
                    </>
                  ) : (
                    ""
                  )}

                  {/* app消息推送 */}
                  {appPush !== "-1" ? (
                    <>
                      <Divider
                        style={{
                          display: `${
                            appletsPush !== "-1" ||
                            sysPush !== "-1" ||
                            todoPush !== "-1"
                              ? ""
                              : "none"
                          }`,
                          margin: `0 0 0 ${Taro.pxTransform(15)}`,
                        }}
                      />
                      <PushOptionItem
                        pushStatus={appPush}
                        eventId={eventId}
                        optionType="appPush"
                        handleChangeSystemStatus={handleChangeSystemStatus}
                      />
                    </>
                  ) : (
                    ""
                  )}

                  {/* 邮件 */}
                  {mailPush !== "-1" ? (
                    <>
                      <Divider
                        style={{
                          display: `${
                            appletsPush !== "-1" ||
                            sysPush !== "-1" ||
                            todoPush !== "-1" ||
                            appPush !== "-1"
                              ? ""
                              : "none"
                          }`,
                          margin: `0 0 0 ${Taro.pxTransform(15)}`,
                        }}
                      />
                      <PushOptionItem
                        pushStatus={mailPush}
                        eventId={eventId}
                        optionType="mailPush"
                        handleChangeSystemStatus={handleChangeSystemStatus}
                      />
                    </>
                  ) : (
                    ""
                  )}

                  {/* 手机短信 */}
                  {smsPush !== "-1" ? (
                    <>
                      <Divider
                        style={{
                          display: `${
                            appletsPush !== "-1" ||
                            sysPush !== "-1" ||
                            todoPush !== "-1" ||
                            appPush !== "-1" ||
                            mailPush !== "-1"
                              ? ""
                              : "none"
                          }`,
                          margin: `0 0 0 ${Taro.pxTransform(15)}`,
                        }}
                      />
                      <PushOptionItem
                        pushStatus={smsPush}
                        eventId={eventId}
                        disabled={true}
                        optionType="smsPush"
                        handleChangeSystemStatus={handleChangeSystemStatus}
                      />
                    </>
                  ) : (
                    ""
                  )}
                </View>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
export default App;

type PushOptionItemProps = {
  disabled?: boolean; //开关可用状态
  pushStatus: string; //当前开关状态
  eventId: string; //事件Id
  optionType: string; //开关类型 appletsPush | appPush...
  handleChangeSystemStatus(
    optionType: string,
    value: boolean,
    eventId: string
  ): void;
};

const optionNames = {
  appletsPush: "公众号消息推送",
  sysPush: "系统提醒推送",
  todoPush: "待办事项推送",
  appPush: "App消息推送",
  mailPush: "邮件",
  smsPush: "手机短信",
};

function PushOptionItem(props: PushOptionItemProps) {
  const {
    disabled = false,
    pushStatus,
    eventId,
    optionType,
    handleChangeSystemStatus,
  } = props;

  return (
    <View className={styles["push-option-item"]}>
      <View className={styles["push-option-name"]}>
        {optionNames[optionType]}
      </View>
      <Switch
        disabled={disabled}
        checked={pushStatus === "1"}
        onChange={(value) => {
          handleChangeSystemStatus(optionType, value, eventId);
        }}
        style={{
          "--width": Taro.pxTransform(72),
          "--height": Taro.pxTransform(42),
          "--checked-color": "#56be56",
        }}
      />
    </View>
  );
}
